import Vue from 'vue'
import VueRouter from 'vue-router'
import Store from "@/store";
import axios from "axios";
import HomeView from '../views/HomeView.vue'
import LoginView from "@/views/LoginView";
/*import {parsePath} from "vue-router/src/util/path";*/
Vue.use(VueRouter)

// 解决编程式路由往同一地址跳转时会报错的情况
const originalPush = VueRouter.prototype.push;
const originalReplace = VueRouter.prototype.replace;

// push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch(err => err);
};

//replace
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalReplace.call(this, location, onResolve, onReject);
  return originalReplace.call(this, location).catch(err => err);
};

const routes = [/*route对象指得是具体信息*/
  {
    path: '/',
    redirect: "/home"
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView,
    // children: [
    //   {
    //     path: "/index",
    //     component: ()=>import("../views/index.vue"),
    //   }
    //]
  },
  {
    path: "/login",
    name: "login",
    component: LoginView
  }
  // {
  //   path: '/about',
  //   name: 'about',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  // }
]

const router = new VueRouter({/*路由管理器对象*/
  routes
})

router.beforeEach((to,form,next)=>{
  /*如果path是/login,to.path,那么直接跳转,next()
  * 如果不是/login,那么就从sessionStorage里取tokenMap
  * 如果tokenMap为null,强制跳转/login,next("/login")*/
  if (to.path==="/login"){
    sessionStorage.clear();
    localStorage.clear();
    next()
    return;
  }
  if (!sessionStorage.getItem("tokenMap")){
    next("/login")
    return;
  }
  /*如果Store.state.user===null,发起请求,url: /menu/menuanduser */
  if (Store.state.user===null){
    axios.get("/menu/menuanduser").then((res)=>{
      /*通过解构表达式把res.data解构出来{data:{resCode,resData}}*/
      const {data:{resCode,resData}}=res;
      console.log(resCode,resData)
      /*校验resCode===2000
      * 1.如果不等于,强制路由跳转回/login
      * 2.如果等于,把resData中的currentUser属性值保存到Store.state.user属性中
      * 把menus属性值保存到Store.state.menu属性*/
      if (resCode!==2000){
        next("/login");
        return;
      }
      Store.commit("setUserData",resData.currentUser);
      Store.commit("setMenuData",resData.menus);
      /*动态构建路由
      * 代表路由信息js对象,通常需要哪些属性
      *  {
         path: "/login",
         name: "login",
         component: LoginView
         }
      * path:指定了触发路由的url,必写 属性值String,route.path来获取该属性的值
      * name:给当前路由信息起了一个别名,可选 属性值:String,route,name
      * component:指定当前路由跳转组件,必写,可以是变量,可以是函数
      * meta:指定了当前路由的额外的信息 属性值为js对象route.meta可选,但是我们需要该属性保存权限标识符*/
      let routes = (resData.menus).filter((item) => {
        return item.path
      }).map((item) => {
        let route = {};
        route.path = item.path;
        let componentDir = item.comDir === "/" ? item.comDir : item.comDir + "/";
        let componentPath = componentDir + item.comName + ".vue";
        console.log(componentPath)
        //../views不能先拼接路由要导入组件的路径中,必须写在import函数中
        route.component = () => import("../views" + componentPath);
        route.meta = {};
        route.meta.title = item.comTitle;
        route.meta.permission = item.permission;
        return route;
      })
      console.log(routes);
      let homeRoute={};
      homeRoute.path='/home';
      homeRoute.name="home";
      homeRoute.component=HomeView;
      homeRoute.children=routes;
      /*动态的添加到路由表中*/
      router.addRoute(homeRoute);
      next();
      return;
    })
  }
  next();
})

export default router
